 
<html>
<head>
	<title>sockte聊天室</title>
	<link href="layer/css/layui.css" rel="stylesheet" type="text/css" media="all"></link>
	<link href="exp/index.css" rel="stylesheet" type="text/css" media="all"></link>
    <meta charset='utf-8'>
</head>

<body onload="connect();">
	<div style="margin:0 auto; width:800px;">
		<div id="content" style="height:400px; width:670px; margin-left:110px; margin-top:50px;overflow-x: hidden;border: 1px solid #ccc; padding:10px;" class="msgone">
 
				<!-- <div class="msg"><span style="color:green; font-width:blod;">【我】：</span>这是一条消息</div> -->
 
		</div>
<br/>
<br/>
	<div style="margin:0 auto; width:800px;">
	<!-- <form class="layui-form" action="#"> -->
		  <div class="layui-form-item layui-form-text"> 
		    <div class="layui-input-block">
		      <span style="color:green; font-width:blod;" id="username"></span><textarea name="desc" id="txt" placeholder="请输入聊天内容..." class="layui-textarea"></textarea>
		    </div>
		  </div>
		  <div class="layui-form-item">
		    <div class="layui-input-block" style="float:right;">
		      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
		      <button class="layui-btn disabled" id="onSubmits" type="button">立即提交</button>
		    </div>
		  </div>
	<!-- </form> -->
	</div>
	</div>

	<div id="userlist"></div>
	<select id="client_list"></seletct>
</body>
</html>
<script type="text/javascript" src="exp/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="layer/layui.js"></script>
<script type="text/javascript" src="exp/iscroll.js"></script>
 <script type="text/javascript">
    if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
    WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
    WEB_SOCKET_DEBUG = true;
    var ws, name, client_list={};

    // 连接服务端
    function connect() {
       // 创建websocket
       ws = new WebSocket("ws://"+document.domain+":7272");
       // ws = new WebSocket("ws://localhost:7272");
       // 当socket连接打开时，输入用户名
       ws.onopen = onopen;
       // 当有消息时根据消息类型显示不同信息
       ws.onmessage = onmessage; 
		console.log(typeof(ws.onmessage));
       ws.onclose = function() {
    	  console.log("连接关闭，定时重连");
          connect();
       };
       ws.onerror = function() {
     	  console.log("出现错误");
       };
    }

    // 连接建立时发送登录信息
    function onopen()
    {
    	// name = "用户"+Math.round(Math.random()*100);
        name ="";
    	// room_id = Math.round(Math.random()*10000);
        room_id = 123456;
        if(!name)
        {
            show_prompt();
        }
        // 登录
        var login_data = '{"type":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"'+room_id+'"}';
        console.log("websocket握手成功，发送登录数据:"+login_data);
        ws.send(login_data);
    }

    // 服务端发来消息时
    function onmessage(e)
    {
		console.log("这是服务端发来的消息");
        console.log(e.data);
        console.dir(e);
        var data = eval("("+e.data+")");
        switch(data['type']){
            // 服务端ping客户端
            case 'ping':
                ws.send('{"type":"pong"}');
                break;;
            // 登录 更新用户列表
            case 'login':
                //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
                say(data['client_id'], data['client_name'],  data['client_name']+' 加入了聊天室', data['time']);
                if(data['client_list'])
                {
                    client_list = data['client_list'];
                }
                else
                {
                    client_list[data['client_id']] = data['client_name']; 
                }
                flush_client_list();
                console.log(data['client_name']+"登录成功");
                $('body').prepend('<blockquote class="layui-elem-quote"><span style="color:red;">【'+data['client_name']+'】</span>上线了</blockquote>');
                break;
            // 发言
            case 'say':
                //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
                say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
                console.log(data);
                break;
            // 用户退出 更新用户列表
            case 'logout':
                //{"type":"logout","client_id":xxx,"time":"xxx"}
                say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
                delete client_list[data['from_client_id']];
                flush_client_list();
        }
    }

    // 输入姓名
    function show_prompt(){  
        name = prompt('输入你的名字：', '');
        if(!name || name=='null'){  
            name = '游客'+Math.round(Math.random()*100);
        }
        $("#username").text(name+":");
    }

    // 提交对话
    function onSubmit() {
      var input = document.getElementById("txt");
      var to_client_id = $("#client_list option:selected").attr("value");
      var to_client_name = $("#client_list option:selected").text();
      ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
      input.value = "";
      input.focus();
    }

    // 刷新用户列表框
    function flush_client_list(){
    	var userlist_window = $("#userlist");
    	var client_list_slelect = $("#client_list");
    	userlist_window.empty();
    	client_list_slelect.empty();
    	userlist_window.append('<h4>在线用户</h4><ul>');
    	client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
    	for(var p in client_list){
            userlist_window.append('<li id="'+p+'">'+client_list[p]+'</li>');
            client_list_slelect.append('<option value="'+p+'">'+client_list[p]+'</option>');
        }
    	$("#client_list").val(select_client_id);
    	userlist_window.append('</ul>');
    }

    // 发言
    function say(from_client_id, from_client_name, content, time){
    	// $("#content").append('<div class="speech_item"><img src="http://lorempixel.com/38/38/?'+from_client_id+'" class="user_icon" /> '+from_client_name+' <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>');
    	$("#content").append('<div class="msg"><span style="color:green; font-width:blod;">【'+from_client_name+'】</span><span style="font-size:10px;">&lt;'+time+'&gt;</span><br/><div style="margin-left:20px; margin-top:10px;">'+content+'</div></div>');
        $('#content').scrollTop( $('#content')[0].scrollHeight ); 
    }

    $(function(){
    	select_client_id = 'all';
	    $("#client_list").change(function(){
	         select_client_id = $("#client_list option:selected").attr("value");
	    });
	 });
    
 
	 

	/* 发送消息*/
	/* function sends(vals){
		var ws = new WebSocket("ws://localhost:7272");
		ws.onopen = function(){
		    console.log("握手成功2");
		    ws.send(vals);
		    ws.onmessage=function(msg){ 
				console.log("推送的消息"+msg);
				console.dir(msg);
			}
			ws.onclose = function(){ console.log("关闭监听");};
		};
	} */
	/* 链接服务端 */
	// var ws = new WebSocket("ws://localhost:7272");
	// ws.onopen = function(){
	// 	console.log("握手成功1");  
	// 	ws.send("发送握手数据");
	// 	ws.onclose = function(){ console.log("关闭监听");};
	// };
		 
    /* 滚动条最底部 */ 

	// $("#onSubmits").on("click",function(){ 
	// 	// var txt = $("#txt").val();
	// 	// connect(); 
			
	// 	onSubmit();
	// 	$('#content').scrollTop( $('#content')[0].scrollHeight ); 
	
	// 	// onmessage(e);
	// });

	// /* 发送消息 */
	$("#txt").on("keyup",function(event){
	//内容不为空加入样式，如果是回车按钮就发送消息
		if($.trim($(this).val())!=""){
			$("#onSubmits").removeClass("disabled");
			if(event.keyCode==13){ 
				onSubmit(); 
				// onmessage(e);
				$('#content').scrollTop( $('#content')[0].scrollHeight ); 
			}
		}else{
		
			$("#onSubmits").addClass("disabled"); 
		}
	}).on("keydown",function(event){
		if(event.keyCode==13){//屏蔽回车键 
			return false;
		}
	}); 
 
</script>